package com.beyondsoft.mcms.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.beyondsoft.mcms.domain.Category;
import com.beyondsoft.mcms.domain.Item;

@RequestMapping("/items")
@Controller
@RooWebScaffold(path = "items", formBackingObject = Item.class, delete = false)
@RooWebFinder
public class ItemController {

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Item item, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, item);
            return "items/create";
        }
        uiModel.asMap().clear();
        Item maxItem = Item.getMaxItemByCategory(item.getCategory());
        Long maxId = item.getCategory().getId();
        if (maxItem != null) {
            maxId = maxItem.getId();
        } else {
            maxId = maxId * 100;
        }
        item.setId(++maxId);
        item.persist();
        return "redirect:/items/" + encodeUrlPathSegment(item.getId().toString(), httpServletRequest);
    }

    @RequestMapping(params = { "find=ByCategory", "form" }, method = RequestMethod.GET)
    public String findItemsByCategoryForm(Model uiModel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.getSession().setAttribute("category", null);
        return findItemsByCategory(null, uiModel);
    }

    @RequestMapping(params = "find=ByCategory", method = RequestMethod.GET)
    public String findItemsByCategory(@RequestParam(value = "category", required = false) Category category, Model uiModel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        int sizeNo = size == null ? 10 : Integer.valueOf(size);
        int pageNo = page == null ? 1 : Integer.valueOf(page);
        if (category != null && (!category.getId().equals(-1))) {
            request.getSession().setAttribute("category", category);
        } else if (page == null || page.length() == 0) {
            category = null;
            request.getSession().setAttribute("category", null);
        } else {
            category = (Category) request.getSession().getAttribute("category");
        }
        uiModel.addAttribute("category", category);
        return list(pageNo, sizeNo, uiModel);
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        uiModel.addAttribute("categorys", Category.findAllCategorys());
        Category category = (Category) uiModel.asMap().get("category");
        int sizeNo = size == null ? 10 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        float nrOfPages = 0.0f;
        if (category == null) {
            uiModel.addAttribute("items", Item.findItemEntries(firstResult, sizeNo));
            nrOfPages = (float) Item.countItems() / sizeNo;
        } else {
            List<Item> items = Item.findItemsByCategory(category).getResultList();
            int lastResult = (items.size() > (sizeNo + firstResult)) ? (sizeNo + firstResult) : items.size();
            uiModel.addAttribute("items", items.subList(firstResult, lastResult));
            nrOfPages = (float) Item.findItemsByCategory(category).getResultList().size() / sizeNo;
        }
        uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        //uiModel.addAttribute("category", category);
        uiModel.addAttribute("find", "ByCategory"); //differ non-query request
        uiModel.addAttribute("selectQueryIds", (category == null ? -1 : category.getId()));
        return "items/list";
    }
}
